package com.koron.auth.aop;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.map.MapUtil;
import com.koron.auth.service.CommonWebService;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.util.ServletUtils;
import com.koron.common.core.business.log.entity.po.LogLoginPo;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.Date;

@Aspect
@Component
@Slf4j
public class LoginLogAop {

    @Autowired
    private CommonWebService service;


    @Pointcut(value = "@annotation(com.koron.auth.aop.LoginLog)")
    private void pointcut(){

    }

    @Around(value = "pointcut()")
    public Object around(ProceedingJoinPoint joinPoint){
        log.info("LoginLogAop:methodName={}",joinPoint.getSignature().getName());
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
            Response response = (Response)proceed;
            int code = response.getCode();
            // 状态为200 表示登录成功，记录日志
            if (HttpStatus.OK.value() == code){
                HttpServletRequest request = ServletUtils.getRequest();
                EamUser eamUser = (EamUser) response.getData();
                InetAddress localHost = InetAddress.getLocalHost();
                String hostAddress = request == null ? localHost.getHostAddress() : IpUtil.getIpAddr(request);
                String hostName = localHost.getHostName();
                Date loginTime = new Date();
                String account = eamUser.getAccount();
                String name = eamUser.getName();
                String appid = eamUser.getAppId();
                LogLoginPo logLoginPo = new LogLoginPo();
                logLoginPo.setId(CodeTools.getCode32());
                logLoginPo.setIp(hostAddress);
                logLoginPo.setHost(hostName);
                logLoginPo.setInTime(loginTime);
                logLoginPo.setAccount(account);
                logLoginPo.setName(name);
                logLoginPo.setAppId(appid);
                Response<String> result = service.saveLogLogin(MapUtil.of(Pair.of("currDs",eamUser.getCurrDs())), logLoginPo);
                log.info("LoginLogAop:around:saveLogLogin:{}",Integer.valueOf(String.valueOf(result)) > 0 ? "success":"fail");
            }
        } catch (Throwable throwable) {
            log.error("LoginLogAop:around:{}",throwable.getMessage());
        }
        return proceed;
    }
}
